import os
from datetime import datetime
from config import load_config
from logger_setup import setup_logging
from redis_utils import RedisClient
from sftp_utils import SFTPSync

def main():
    # 初始化日志
    success_logger, error_logger = setup_logging()
    
    try:
        # 加载配置
        CONFIG = load_config()
        KEYS_TO_READ = CONFIG['keys_to_read']
        DATA_DIR = 'data'
        
        # 确保数据目录存在
        if not os.path.exists(DATA_DIR):
            os.makedirs(DATA_DIR)
        
        # 生成带时间戳的文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M')
        csv_filename = f'{timestamp}_config.csv'
        csv_filepath = os.path.join(DATA_DIR, csv_filename)
        
        # 连接Redis并获取数据
        redis_client = RedisClient(CONFIG['redis'])
        redis_client.connect()
        csv_data = redis_client.get_keys_data(KEYS_TO_READ)
        redis_client.close()
        
        # 写入CSV数据，本地文件写入后不立即删除，可通过批处理删除10天前文件
        with open(csv_filepath, 'w', encoding='utf-8') as f:
            f.write('时间,key值,value值\n')
            for row in csv_data:
                f.write(','.join(row) + '\n')
        success_logger.info(f'CSV数据已保存至: {csv_filepath}')
        
        # SFTP上传
        sftp_sync = SFTPSync(
            host=CONFIG['sftp']['host'],
            port=CONFIG['sftp']['port'],
            username=CONFIG['sftp']['username'],
            password=CONFIG['sftp']['password']
        )
        sftp_sync.connect()
        # 清空远程目录，上传前先清空，星环只能全量读取
        # 若远端数据读取失败，可注释以下一行代码，手动批量上传csv文件至远端完成读取后再取消注释
        sftp_sync.clear_remote_directory(CONFIG['sftp']['remote_dir'])
        # 上传文件，在上传文件后的5分钟内完成星环对csv文件的读取
        sftp_sync.upload_file(csv_filepath, CONFIG['sftp']['remote_dir'])
        sftp_sync.close()
        
    except Exception as e:
        error_logger.error(f'执行失败: {str(e)}', exc_info=True)
        print(f'执行失败: {str(e)}')

if __name__ == '__main__':
    main()